#ifndef _SCLIST_H_
#define _SCLIST_H_


#include"utili.h"

#define SCListElem_Type int
typedef struct SCListNode {
	SCListElem_Type data;
	struct SCListNode* next;
}SCListNode;

typedef SCListNode* SCList;



void SCListInit(SCList* phead);
void SCListPushBack(SCList* phead, SCListElem_Type v);
void SCListPushFront(SCList* phead, SCListElem_Type v);
void SCListDeleteVsl(SCList* phead, SCListElem_Type v);
void SCListSort(SCList* phead);



void SCListInit(SCList* phead) {
	*phead = NULL;
}
void SCListPushBack(SCList* phead, SCListElem_Type v) {
	SCListNode* s = (SCListNode*)malloc(sizeof(SCListNode));
	assert(s != NULL);
	s->data = v;
	if (*phead == NULL) {
		*phead = s;
		s->next = *phead;
		return;
	}
	SCListNode* p = *phead;
	while (p->next != *phead) {
		p = p->next;
	}
	p->next = s;
	s->next = *phead;
}
void SCListPushFront(SCList* phead, SCListElem_Type v) {
	SCListNode* s = (SCListNode*)malloc(sizeof(SCListNode));
	assert(s!=NULL);
	s->data = v;
	if (*phead == NULL) {
		*phead = s;
		s->next = *phead;
		return;
	}
	SCListNode* p = *phead;
	while (p ->next!= *phead) {
		p = p->next;
	}
	s->next = (*phead)->next;
	*phead = s;
	p->next = *phead;
}


void SCListDeleteVsl(SCList* phead, SCListElem_Type v) {
	assert(*phead != NULL);
	SCListNode* pr = NULL, * p = *phead;

	if ((*phead)->data == v) {
		SCListNode* last = *phead;
		while (last->next != *phead) {
			last = last->next;
			*phead = p->next;
			last->next = *phead;
		}

	}
	else {
		while (p->next != *phead && p->data != v) {
			pr = p;
			p = p->next;
		}

		if (p->data == v) {
			pr->next = p->next;
		}
		}
	free(p);
}
//void SCListSort(SCList* phead) {
//	if (*phead == NULL || ( * phead)->next == *phead) {
//		return;
//	}
//	SCListNode* p = (*phead)->next,*pr=NULL;
//	(*phead) -> next = NULL;
//	
//	while (p != *phead) {
//		SCListNode* q = p->next;
//		
//		SCListNode* temp = *phead;
//		while (temp != NULL && temp ->data < p->data) {
//			pr = temp;
//			temp = temp->next;
//		}
//		if (pr == NULL) {
//			p->next = *phead;
//			*phead = p;
//		}
//		else{
//			p->next = temp;
//			pr->next = p;
//			}
//	 
//		p = q;
//	}
//	SCListNode* r = *phead;
// while (r->next!=NULL) {
//r = r->next;
//}
//	r->next = *phead;
//}


void SCListSort(SCList* phead) {
	if (*phead == NULL || (*phead)->next == *phead) {
		return;
	}
	SCListNode* p = (*phead)->next;
	(*phead)->next = *phead;

	while (p != *phead) {
		SCListNode* q = p->next;

		SCListNode* temp = *phead;
		if (p->data < temp->data) {
			p->next = temp;
			*phead = p;
		}
		else {
			while (temp != NULL && temp->data < p->data) {

				temp = temp->next;
			}
			{
				p->next = temp->next;
				pr->next = p;
			}

			p = q;
		}

	
		SCListNode* r = p->next;
		r->next = *phead;
	}
}
#endif // !_SCLIST_H_

